<template>
  <div class="container">
    <el-form
      :inline="true"
      :model="params"
      label-width="70px"
      label-position="left"
      size="mini"
      class="demo-form-inline"
      style="padding-top: 18px;"
      @submit.native.prevent
    >
      <el-form-item label="活动ID">
        <el-input clearable v-model="params.id" placeholder="活动ID" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="活动名称">
        <el-input clearable v-model="params.activityName" placeholder="活动名称" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="申请人">
        <el-input clearable v-model="params.applyName" placeholder="申请人" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="params.status" placeholder="请选择">
          <el-option value label="请选择"></el-option>
          <el-option value="1" label="初始"></el-option>
          <el-option value="2" label="进行中"></el-option>
          <el-option value="3" label="已结束"></el-option>
          <el-option value="4" label="已作废"></el-option>
          <el-option value="5" label="发放失败"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="领券类型">
        <el-select v-model="params.collectType" placeholder="请选择">
          <el-option label="请选择" value></el-option>
          <el-option label="定向发放" value="0"></el-option>
          <el-option label="直接领取" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="批次ID">
        <el-input clearable v-model="params.batchId" placeholder="批次ID" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="活动时间">
        <el-date-picker
          v-model="params.activityDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
        <!-- <el-input v-model="params.activityTime" placeholder="活动时间" class="the-input"></el-input> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="doSearch">查询</el-button>
        <!-- <el-button type="primary" @click="toAddActivity">新增活动</el-button> -->
      </el-form-item>
    </el-form>
    <div class="button-field">
      <!-- <el-button size="small" type="primary" @click="doSearch">查询</el-button> -->
      <el-button size="small" type="primary" @click="toAddActivity">新增活动</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%" border size="small" height="300" stripe>
      <el-table-column prop="id" label="活动ID" width="180"></el-table-column>
      <el-table-column prop="activityName" label="活动名称" width="180"></el-table-column>
      <el-table-column prop="collectType" label="领券类型" width="180">
        <template slot-scope="{row}">{{row.collectType === 1 ? '直接领取' : '定向发放'}}</template>
      </el-table-column>
      <el-table-column prop label="活动时间" width="180">
        <template
          slot-scope="{row}"
        >{{(row.startTime || '') +(row.startTime ? '-' : '')+( row.endTime || '')}}</template>
      </el-table-column>
      <el-table-column prop label="状态" width="180">
        <template slot-scope="{row}">{{row.status | statusFilter }}</template>
      </el-table-column>
      <el-table-column prop="applyName" label="申请人" width="180"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column fixed="right" label="操作" width="350" align="center">
        <template slot-scope="{row}">
          <el-button type="text" size="small" @click="toDetail(row)">查看</el-button>
          <el-button
            type="text"
            size="small"
            v-if="row.status === 1 || row.status === 2"
            @click="toEdit(row)"
          >修改</el-button>
          <el-button
            type="text"
            size="small"
            v-if="(row.status === 1 || row.status === 2) && row.collectType !== 1"
            @click="importUserList(row)"
          >导入用户列表</el-button>
          <el-button
            type="text"
            size="small"
            v-if="(row.status === 1 || row.status === 2) && row.collectType !== 1"
            @click="showProvideDetail(row)"
          >查看发放明细</el-button>
          <el-button type="text" size="small" v-if="row.status === 1" @click="doCancel(row)">作废</el-button>
          <el-button type="text" size="small" v-if="row.status === 2" @click="forceEnd(row)">强制结束</el-button>
          <el-button type="text" size="small" @click="showLog(row)">日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-area" style>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        :page-count="pageCount"
      ></el-pagination>
    </div>
    <el-dialog title="优惠券活动日志" :visible.sync="dialogVisible" width="800">
      <el-table :data="logs" border size="small" stripe>
        <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
        <el-table-column width="100" prop="createBy" label="操作人"></el-table-column>
        <el-table-column width="150" prop="operateDesc" label="操作类型"></el-table-column>
        <el-table-column prop="createTime" label="时间"></el-table-column>
        <el-table-column prop="remark" label="操作说明" width="100"></el-table-column>
      </el-table>
      <div class="pagination-area">
        <el-pagination
          background
          @size-change="handleLogSizeChange"
          @current-change="handleLogCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="logParams.pageSize"
          :current-page.sync="logParams.pageIndex"
          layout="total, sizes, prev, pager, next, jumper"
          :total="logParams.totalCount"
          :page-count="logParams.pageCount"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="查看发放明细" :visible.sync="showBindingDetail" width="900">
      <el-form size="mini" :inline="true" @submit.native.prevent>
        <el-form-item label="手机号码">
          <el-input clearable placeholder="手机号码" v-model="bindParams.phone" style="width: 150px;" />
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary" @click="searchBindDetailList">查询</el-button>
        </el-form-item>
        <el-form-item>
          导入总量
          <span>{{bindParams.totalCount}}</span>，成功发放
          <span>{{bindParams.successCount}}</span>，待发放
          <span>{{bindParams.waitingCount}}</span>，发放失败
          <span>{{bindParams.failCount}}</span>
        </el-form-item>
      </el-form>
      <el-table :data="bindParams.bindDetailList" border size="small" stripe>
        <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
        <el-table-column width="100" prop="userId" label="用户ID"></el-table-column>
        <el-table-column width="150" prop="phone" label="手机号码"></el-table-column>
        <el-table-column label="发放状态">
          <template slot-scope="{row}">
            <span>{{ row.status | statusFormat }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-area">
        <el-pagination
          background
          @size-change="handleListSizeChange"
          @current-change="handleListCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="bindParams.pageSize"
          :current-page.sync="bindParams.pageIndex"
          layout="total, sizes, prev, pager, next, jumper"
          :total="bindParams.totalCount"
          :page-count="bindParams.pageCount"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showBindingDetail = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="导入用户列表" :visible.sync="showImportUserList" width="500">
      <h3 style="margin: 0 0 10px 0;">
        当前批次优惠券剩余数量：
        <span>{{freeCount}}</span>
      </h3>
      <!--  :on-success="onSuccess"-->
      <el-upload
        class="upload-demo"
        ref="upload"
        accept=".xlsx, .xls"
        :before-upload="beforeUpload"
        :http-request="uploadFile"
        :action="uploadAction"
        :auto-upload="false"
      >
        <el-button slot="trigger" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" type="success" @click="downTemplate">下载模板</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doUpload">确定上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getActivityList } from '@/api/coupon/activity';
import {
  getActivityLog,
  forceEndActivity,
  cancelActivity,
  getBindingDetail,
  getFreeCountByActiveId,
  uploadUserList,
} from '@/api/coupon'

export default {
  name: "couponList",
  data() {
    return {
      // 用于显示或隐藏日志弹窗
      dialogVisible: false,
      showImportUserList: false,
      showBindingDetail: false,
      uploadAction: `/managerAPI/coupon-activity/binding/`,
      body: {
        id: "",
      },
      freeCount: 0,
      // 参数
      params: {
        // 每页条数
        pageSize: 10,
        // 页码
        pageIndex: 1,
        // 活动ID
        id: "",
        // 活动名称
        activityName: "",
        // 申请人
        applyName: "",
        // 状态
        status: "",
        // 优惠券批次id
        batchId: "",
        // 领券类型 1定向发放、2直接领取（非必填）
        collectType: "",
        // 活动时间
        startTime: "",
        endTime: "",
        activityDate: [],
      },
      totalCount: 0,
      pageCount: 0,
      logs: [],
      logParams: {
        pageIndex: 1,
        pageSize: 10,
        // 总条目数
        totalCount: 0,
        // 总页数
        pageCount: 0,
        rowId: "",
      },
      bindParams: {
        pageIndex: 1,
        pageSize: 10,
        // 总条目数
        totalCount: 0,
        // 总页数
        pageCount: 0,
        phone: "",
        bindDetailList: [],
        totalCount: 0,
        failCount: 0,
        successCount: 0,
        waitingCount: 0,
        // 活动id
        id: "",
      },
      totalCount: 100,
      tableData: [],
    };
  },
  watch: {
    "params.activityDate": {
      handler: function (val) {
        this.params.startTime = val[0] || "";
        this.params.endTime = val[1] || "";
      },
      deep: true,
    },
  },

  filters: {
    statusFilter: function (val) {
      // 0请选择、1初始、2进行中、3已结束、4已作废、5 发放失败
      const types = [
        "请选择",
        "初始",
        "进行中",
        "已结束",
        "已作废",
        "发放失败",
      ];
      return types[val];
    },
    statusFormat: function (val) {
      return ["", "待发放", "发放失败", "发放成功"][val];
    },
  },
  methods: {
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageIndex = 1;

      this.getActivityList();
    },
    handleCurrentChange(pageIndex) {
      this.params.pageIndex = pageIndex;
      this.getActivityList();
    },
    async uploadFile(params) {
      const that = this;
      const formData = new FormData();
      formData.append("file", params.file);
      uploadUserList(params.action, formData).then((res) => {
        if (res && res.type === "application/json") {
          const reader = new FileReader();
          reader.readAsText(res, "utf-8");
          reader.onload = function (e) {
            const data = JSON.parse(reader.result);
            if (data.code === 200) {
              that.showImportUserList = false;
              that.$message.success("上传成功");
              that.doSearch();
              // 清理文件
              // that.$refs.upload.clearFiles();
            } else {
              that.$message.error(data.message);
            }
          };
        } else {
          const blob = res;
          this.$message.error("上传失败!");
          const a = document.createElement("a");
          const filename = "上传失败错误信息.xlsx";
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // for IE
            window.navigator.msSaveOrOpenBlob(blob, filename);
          } else {
            var url = window.URL.createObjectURL(blob);
            a.style.display = "none";
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);

            that.doSearch();
          }
        }
      })
    },
    onSuccess(response, file, fileList) {
      console.log(file);
      console.log(fileList);
      if (response.code === 200) {
        this.showImportUserList = false;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败!");

        const filename = "上传失败错误信息.xlsx";
        const blob = new Blob([response], {
          type: "application/octet-stream;charset=utf-8",
        });
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, filename);
        } else {
          const a = document.createElement("a");
          a.download = filename;
          a.style.display = "none";
          a.href = URL.createObjectURL(blob);
          document.body.appendChild(a);
          a.click();
          // document.body.removeChild(a);
        }
      }
    },
    doUpload() {
      const that = this;
      this.uploadAction =
        "/managerAPI/coupon-activity/binding/" + this.currentRow.id;
      this.$nextTick(function () {
        that.$refs.upload.submit();
      });
    },
    beforeUpload() {
      this.uploadAction =
        "/managerAPI/coupon-activity/binding/" + this.currentRow.id;
    },
    // 强制结束
    forceEnd(row) {
      this.$confirm("请确认是否强制结束当前活动", "强制结束确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          forceEndActivity(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "操作成功!",
                type: "success",
              });
              this.doSearch();
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: "error",
              });
            }
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    toAddActivity() {
      this.$router.push({
        path: "/addactivity",
        query: {
          viewType: "add",
        },
      });
    },
    doSearch() {
      this.params.pageIndex = 1;
      this.getActivityList();
    },
    getActivityList() {
      const loading = this.$loading({
        lock: true,
        text: "请稍等...",
      });
      // 加载活动列表
      getActivityList({
        activityName: this.params.activityName.trim(),
        applyName: this.params.applyName.trim(),
        batchId: this.params.batchId,
        collectType: this.params.collectType,
        endTime: this.params.endTime,
        id: this.params.id,
        startTime: this.params.startTime,
        status: this.params.status,
        pageSize: this.params.pageSize,
        pageIndex: this.params.pageIndex,
      }).then((res) => {
        loading.close();
        const { result } = res;
        if (result) {
          this.tableData = result.records;
          this.totalCount = result.total;
          this.pageCount = result.pages;
        }
      });
    },
    // 显示日志
    // showLog() {
    //   this.dialogVisible = true;
    // },
    getLogs() {
      getActivityLog({
        id: this.logParams.rowId,
        type: 1,
        pageIndex: this.logParams.pageIndex,
        pageSize: this.logParams.pageSize,
      }).then((res) => {
        if (res.code === 200) {
          this.logs = res.result.records;
          this.logParams.totalCount = res.result.total;
          this.logParams.pageCount = res.result.pages;
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
    },
    showLog(row) {
      this.logParams.rowId = row.id;
      getActivityLog({
        id: this.logParams.rowId,
        type: 1,
        pageIndex: this.logParams.pageIndex,
        pageSize: this.logParams.pageSize,
      }).then((res) => {
        if (res.code === 200) {
          this.logs = res.result.records;
          this.logParams.totalCount = res.result.total;
          this.logParams.pageCount = res.result.pages;
          this.dialogVisible = true;
          console.log(res);
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      });
      // this.dialogVisible = true;
    },
    handleLogSizeChange(pageSize) {
      this.logParams.pageSize = pageSize;
      this.logParams.pageIndex = 1;

      this.getLogs();
    },
    handleLogCurrentChange(pageIndex) {
      this.params.pageIndex = pageIndex;
      this.getLogs();
    },
    getBindingDetailList() {
      getBindingDetail(this.bindParams.pageIndex, this.bindParams.pageSize, {
        phone: this.bindParams.phone,
        id: this.bindParams.id,
      }).then((res) => {
        if (res.code === 200) {
          this.bindParams.bindDetailList =
            res.result.bindingDetailVoPage.records;
          this.bindParams.totalCount = res.result.bindingDetailVoPage.total;
          this.bindParams.pageCount = res.result.bindingDetailVoPage.pages;
          // this.bindParams.totalCount = res.result.bindingDetailVoPage.totalCount;
          this.bindParams.failCount = res.result.failCount;
          this.bindParams.successCount = res.result.successCount;
          this.bindParams.waitingCount = res.result.waitingCount;
        } else {
          this.bindParams.bindDetailList = [];
        }
      });
    },
    searchBindDetailList(id) {
      this.bindParams.pageIndex = 1;
      this.bindParams.id = id;
      this.getBindingDetailList();
    },
    handleListSizeChange(pageSize) {
      this.bindParams.pageSize = pageSize;
      this.bindParams.pageIndex = 1;

      this.getBindingDetailList();
    },
    handleListCurrentChange(pageIndex) {
      this.bindParams.pageIndex = pageIndex;
      this.getBindingDetailList();
    },
    // 显示发放明细
    showProvideDetail(row) {
      this.showBindingDetail = true;
      this.searchBindDetailList(row.id);
    },
    // 导入用户列表
    importUserList(row) {
      this.currentRow = row;
      // 清除上传历史记录
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      // 获取剩余数量
      getFreeCountByActiveId(row.id).then((res) => {
        this.showImportUserList = true;
        if (res.code === 200) {
          this.freeCount = res.result;
        } else {
          this.freeCount = 0;
        }
      });
    },
    // 编辑
    toEdit(row) {
      this.$router.push({
        path: "/addactivity",
        query: {
          viewType: "edit",
          id: row.id,
        },
      });
    },
    // 明细
    toDetail(row) {
      this.$router.push({
        path: "/addactivity",
        query: {
          viewType: "detail",
          id: row.id,
        },
      });
    },
    doCancel(row) {
      this.$confirm("请确认是否作废当前优惠券批次？", "作废确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 确定
        cancelActivity(row.id).then((res) => {
          if (res.code === 200) {
            this.$message.success("操作成功!");
            this.doSearch();
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    // 下载模板文件
    downTemplate() {
      window.open("/user.xlsx");
    },
  },
  mounted() {
    this.params.pageIndex = 1;
    // 加载优惠券列表
    this.getActivityList();
    // this.getBindingDetailList();
  },
};
</script>

<style lang="scss">
</style>